package org.example.server.product.controller;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.IdUtil;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.example.server.user.bean.ResultBean;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

@Slf4j
@RestController
@RequestMapping("file")
public class FileController {

    @RequestMapping("upload")
    public ResultBean upload(@RequestParam("file") MultipartFile file) throws IOException {

        String originalFilename = file.getOriginalFilename();
        assert originalFilename != null;
        String fixName = originalFilename.substring(originalFilename.lastIndexOf("."));
        String name =  IdUtil.getSnowflakeNextId() + fixName;

        file.transferTo(new File("d:\\upload\\"+name));

        return new ResultBean(200, "上传成功", name);
    }

    @RequestMapping("get")
    public void get(@RequestParam("name") String name, HttpServletResponse httpServletResponse) throws IOException {

        IoUtil.copy(new FileInputStream("d:\\upload\\"+name),httpServletResponse.getOutputStream());

    }
}
